package com.polito.mad.bikeponyapp.activity;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.polito.mad.bikeponyapp.R;
import com.polito.mad.bikeponyapp.persistence.DeliveriesRepository;
import com.polito.mad.bikeponyapp.persistence.DeliveryItem;
import com.polito.mad.bikeponyapp.persistence.RepositoryHolder;
import com.polito.mad.bikeponyapp.service.ServerCommunicationService;
import com.polito.mad.bikeponyapp.util.AsyncTaskForResultMessage;
import com.polito.mad.bikeponyapp.util.ResultMessage;

public class DeliveryActivity extends Activity {

	private static final String ITEM_ID_PARAM_NAME = "itemId";
	private long itemId = -1;
	private DeliveriesRepository deliveryRepo;
	public static final int FEEDBACK_REQUEST_CODE = 2222;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery);
        
		setFinishOnTouchOutside (false);
		deliveryRepo = ((RepositoryHolder)getApplication()).getDeliveriesRepository();
		if(savedInstanceState!=null && savedInstanceState.containsKey(ITEM_ID_PARAM_NAME))
		{
			itemId = savedInstanceState.getLong(ITEM_ID_PARAM_NAME);
		}
		else
		{
			String notif_del_param = getString(R.string.delivery_id_notification_intent_param);
			Bundle myBundle = this.getIntent().getExtras();
			if(myBundle != null && myBundle.containsKey(notif_del_param))
			{
				itemId = myBundle.getLong(notif_del_param);
			}
			
		}
		final DeliveryItem deliveryItemDelivery = deliveryRepo.get(itemId);
		if(deliveryItemDelivery==null)
			return;
			
		Button cancelBtn = (Button) findViewById(R.id.delivery_activity_cancel_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		Button okBtn = (Button) findViewById(R.id.delivery_activity_ok_btn);
		okBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				
				EditText eT = (EditText) findViewById(R.id.delivery_activity_edit_text) ;
				
				if(eT.getText().toString().isEmpty())
				{
					Toast toast = Toast.makeText(DeliveryActivity.this, getString(R.string.delivery_code_not_entered), Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL, 0, 0);
					toast.show();
					return;
				}
				
				
				verifyCode(deliveryItemDelivery);
			}
		});
		//deliveryRepo = ((RepositoryHolder)getApplication()).getRepository();
    }
    
    @Override
	protected void onResume() {
		super.onResume();
		
		EditText edText = (EditText) findViewById(R.id.delivery_activity_edit_text);
		boolean bFocus = edText.requestFocus();
		
		if(bFocus)
		{
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
            
			//InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    //mgr.showSoftInput(edText, 0);
		    			
		}
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		EditText edText = (EditText) findViewById(R.id.delivery_activity_edit_text);
		boolean bFocus = edText.requestFocus();
		
		if(bFocus)
		{
			InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    mgr.hideSoftInputFromWindow(edText.getWindowToken(), 0);
		}
		
	}
	
    private boolean verifyCode(final DeliveryItem deliveryItemDelivery)
    {
    	boolean result = false;
    	
    	StringBuilder b = new StringBuilder();
		b.append(getString(R.string.server_com_protocol))
		.append("://")
		.append(getString(R.string.server_host))
		.append(":")
		.append(getString(R.string.server_port))
		.append(getString(R.string.server_services_context_path))
		.append(getString(R.string.server_services_agent_path))
		.append(getString(R.string.server_services_agent_verify_delivery));

		AsyncTaskForResultMessage asyncTask = new AsyncTaskForResultMessage(b.toString(), true, new AsyncTaskForResultMessage.OnTaskCompletionListener() {
			
			@Override
			public void onTaskEnded(ResultMessage resultMessage) {
				
				if(resultMessage.getStatusCode() == ResultMessage.STATUS_OK)
				{
					
					NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
					mNM.cancel(ServerCommunicationService.ProximityIntentReceiver.DELIVERY_POINT_REACHED_TASK_NOTIFICATION_ACTION,ServerCommunicationService.ProximityIntentReceiver.DELIVERY_POINT_NOTIFICATION_ID);
					
					//code verified form the server
					
					EditText edText = (EditText) findViewById(R.id.delivery_activity_edit_text);
					boolean bFocus = edText.requestFocus();
					
					if(bFocus)
					{
						InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					    mgr.hideSoftInputFromWindow(edText.getWindowToken(), 0);
					}
					
					
					try {

						Toast toast = Toast.makeText(DeliveryActivity.this, getString(R.string.delivery_code_verified), Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL, 0, 0);
						toast.show();
						
						Intent myIntent = new Intent(getApplicationContext(), FeedbackActivity.class);
						myIntent.putExtra(getString(R.string.delivery_id_notification_intent_param), deliveryRepo.get(itemId).getDeliveryId());
						startActivityForResult(myIntent,FEEDBACK_REQUEST_CODE);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				else
				{
					showProgress(false);
					
					Toast toast = Toast.makeText(DeliveryActivity.this, getString(R.string.delivery_code_not_correct), Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL, 0, 0);
					toast.show();
				}
			}
		});
		
		ContentValues cv = new ContentValues();
		String agentId = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.userid_pref), "");
		cv.put("agentId", agentId);
		cv.put("deliveryId", deliveryItemDelivery.getDeliveryId());
		
		EditText eT = (EditText) findViewById(R.id.delivery_activity_edit_text) ;
		cv.put("deliveryCode", eT.getText().toString());
		
		asyncTask.execute(cv);
		
		showProgress(true);
		
    	
    	return result;
    }

    private void showProgress(boolean bShow)
	{
		//if show progress then hide all buttons and show progress widget
		int myViewState = bShow?View.GONE:View.VISIBLE;
		
		Button cancelBtn = (Button) findViewById(R.id.delivery_activity_cancel_btn);
		cancelBtn.setVisibility(myViewState);
		
		Button okBtn = (Button) findViewById(R.id.delivery_activity_ok_btn);
		okBtn.setVisibility(myViewState);
		
		EditText eT = (EditText) findViewById(R.id.delivery_activity_edit_text) ;
		eT.setVisibility(myViewState);
		
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		if(bShow)
		{		
			imm.hideSoftInputFromWindow(eT.getWindowToken(), 0);
		}
		else
		{
			imm.showSoftInput(eT, 0);
		}
		
		ProgressBar pBar = (ProgressBar) findViewById(R.id.delivery_activity_progress_bar) ;
		pBar.setVisibility(bShow?View.VISIBLE:View.GONE);
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.delivery, menu);
        return true;
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	outState.putLong(ITEM_ID_PARAM_NAME, itemId);
    	super.onSaveInstanceState(outState);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode==FEEDBACK_REQUEST_CODE && resultCode==RESULT_OK)
    	{
    		DeliveryItem dItem = deliveryRepo.get(itemId);
    		if(dItem!= null)//item may already been deleted by service as a result of status update.
    			deliveryRepo.delete(dItem);
    		
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(DeliveryActivity.this);
			Editor editor = pref.edit();
			editor.putBoolean(getString(R.string.delivery_status_updated), true);
			editor.commit();
    		
			setResult(RESULT_OK);
    		closeDeliveryActivity();
    	}
    }
    private void closeDeliveryActivity() {
		PreferenceManager.getDefaultSharedPreferences(this).edit()
		.putBoolean(getString(R.string.notification_set_icon), false)
		.commit();
		setResult(RESULT_OK);
		finish();
	}
}
